package yt.kpool.activity.home;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.LineChart;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import yt.kpool.R;
import yt.kpool.base.BaseApplication;
import yt.kpool.bean.CurrencyList;
import yt.kpool.bean.LineChartTestBean;
import yt.kpool.bean.PoolCoinDetailsBean;
import yt.kpool.bean.PowCoinChartBean;
import yt.kpool.network.HttpUtils;
import yt.kpool.network.MyGson;
import yt.kpool.network.NetHelperNew;
import yt.kpool.util.DynamicLineChartDetailManager;
import yt.kpool.util.NetWorkUtil;
import yt.kpool.util.SPUtil;
import yt.kpool.util.ToastUtil;
import yt.kpool.util.Util;
import yt.kpool.util.imageUtil.GlideUtil;
import yt.kpool.view.dialog.ErrorDialog;
import yt.kpool.view.dialog.LoadingDialog;
import yt.kpool.view.pop.CurrencyPopupWindow;

/**
 * 主流币详情
 */
public class MainstreamCurrencyDetaiAc extends AppCompatActivity {
    @BindView(R.id.tv_currrncyname)
    TextView tv_currrncyname;
    @BindView(R.id.iv_curreney)
    ImageView iv_curreney;
    @BindView(R.id.tv_PriceTrend)
    ImageView iv_PriceTrend;
    @BindView(R.id.ll_currency)
    LinearLayout ll_currency;
    @BindView(R.id.dynamic_chart2)
    LineChart mChart2;
    @BindView(R.id.tv_minue)
    TextView tv_minue;
    @BindView(R.id.tv_day)
    TextView tv_day;
    @BindView(R.id.mywitcher)
    Switch mywitcher;
    @BindView(R.id.tv_address1)
    TextView tv_address1;
    @BindView(R.id.tv_address2)
    TextView tv_address2;
    @BindView(R.id.tv_address3)
    TextView tv_address3;
    @BindView(R.id.ll_address2)
    LinearLayout ll_address2;
    @BindView(R.id.ll_address3)
    LinearLayout ll_address3;
    @BindView(R.id.tv_NetworkHashrate)
    TextView tv_NetworkHashrate;
    @BindView(R.id.tv_PoolHashrate)
    TextView tv_PoolHashrate;
    @BindView(R.id.tv_Algorithm)
    TextView tv_Algorithm;
    @BindView(R.id.tv_NetworkDifficulty)
    TextView tv_NetworkDifficulty;
    @BindView(R.id.tv_Price)
    TextView tv_Price;
    @BindView(R.id.tv_NextDifficulty)
    TextView tv_NextDifficulty;
    @BindView(R.id.tv_NextDifficultyTime)
    TextView tv_NextDifficultyTime;
    @BindView(R.id.tv_CostRate)
    TextView tv_CostRate;
    @BindView(R.id.tv_StartPayAmount)
    TextView tv_StartPayAmount;
    @BindView(R.id.tv_PayTime)
    TextView tv_PayTime;
    @BindView(R.id.tv_ThroughputUnit)
    TextView tv_ThroughputUnit;
    @BindView(R.id.tv_Throughput)
    TextView tv_Throughput;
    @BindView(R.id.tv_rmoney)
    TextView tv_rmoney;
    @BindView(R.id.tv_ThroughputU)
    TextView tv_ThroughputU;
    @BindView(R.id.tv_u)
    TextView tv_u;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_title1)
    TextView tv_title1;
    @BindView(R.id.tv_title2)
    TextView tv_title2;
    @BindView(R.id.edit)
    EditText edit;
    @BindView(R.id.tv_Prompt)
    TextView  tv_Prompt;
    @BindView(R.id.ly_Prompt)
    LinearLayout  ly_Prompt;

    private  String code="";
    private String day="30";
    private List<CurrencyList.DataBean> currencyListData;
    private CurrencyPopupWindow currencyPopupWindow;//币种选择
    private DynamicLineChartDetailManager dynamicLineChartManager2;
    private LoadingDialog loadingDialog;
    private int currencyId=0;//币种id
    private PoolCoinDetailsBean.DataBean dataBean;
    private SPUtil spUtil;
    private int kind=0;
    public static void start(Context mactivity, String position,String code,String icon) {
        Intent intent = new Intent(mactivity, MainstreamCurrencyDetaiAc.class);
        intent.putExtra("position", position);
        intent.putExtra("code", code);
        intent.putExtra("icon", icon);
        mactivity.startActivity(intent);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mainstreamcurrencydetail);
        ButterKnife.bind(this);
        init();
        getCurrrencyData();

     }

    /**
     * 获取详情的网络数据
     */
    private void getData()
    {

        if(NetWorkUtil.checkNet(MainstreamCurrencyDetaiAc.this))
        {
            NetHelperNew.PoolCoinDetails("" + currencyId, "", new HttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String data) {
                    Log.i("-->", "矿池详情数据：" + data);
                    loadingDialog.dismiss();
                    PoolCoinDetailsBean poolCoinDetailsBean = MyGson.getInstance().fromJson(data, PoolCoinDetailsBean.class);


                    if (poolCoinDetailsBean.getType() == 1) {
                        dataBean = poolCoinDetailsBean.getData();
                        String[] split = dataBean.getMiningUrl().split(",");
                        ll_address2.setVisibility(View.GONE);
                        ll_address3.setVisibility(View.GONE);
                        for (int i = 0; i < split.length; i++) {

                            if (i == 0) {
                                tv_address1.setText("" + split[i]);
                            }

                            else if (i == 1) {
                                tv_address2.setText("" + split[i]);
                                ll_address2.setVisibility(View.VISIBLE);
                            }
                            else if (i == 2) {
                                tv_address3.setText("" + split[i]);
                                ll_address3.setVisibility(View.VISIBLE);
                            }


                            edit.setText("1");
                            tv_NetworkHashrate.setText(dataBean.getNetworkHashrate());
                            tv_PoolHashrate.setText(dataBean.getPoolHashrate());
                            tv_Algorithm.setText(dataBean.getAlgorithm());
                            tv_NetworkDifficulty.setText(dataBean.getNetworkDifficulty());
                            tv_NextDifficulty.setText(dataBean.getNextDifficulty());
                            tv_NextDifficultyTime.setText(dataBean.getNextDifficultyTime());
                            tv_ThroughputUnit.setText(dataBean.getThroughputUnit());
                            tv_Throughput.setText(Util.GetNumber(dataBean.getThroughput()+""));
                            tv_ThroughputU.setText(tv_currrncyname.getText().toString().toUpperCase());
                            if(dataBean.getPrompt().isEmpty())
                            {
                                ly_Prompt.setVisibility(View.GONE);
                            }
                            else
                            {
                                ly_Prompt.setVisibility(View.VISIBLE);
                                tv_Prompt.setText(dataBean.getPrompt());
                            }

                            if(dataBean.getPriceTrend()>0)
                            {
                                iv_PriceTrend.setImageResource(R.mipmap.shangzhang);
                            }
                            else if(dataBean.getPriceTrend()<0)
                            {
                                iv_PriceTrend.setImageResource(R.mipmap.xiadie);
                            }
                            double t = dataBean.getThroughput() * dataBean.getPrice();//美元的日理论收益
                            if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 1) {
                                BigDecimal bi1 = new BigDecimal(dataBean.getPrice());

                                BigDecimal bi2 = new BigDecimal(dataBean.getExchange() + "");
                                double s = bi1.multiply(bi2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                                BigDecimal bi3 = new BigDecimal(t);
                                double f = bi3.multiply(bi2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                                //人民币币价
                                tv_Price.setText("￥" + s);
                                tv_rmoney.setText("≈ ￥ "+Util.Multiplication(s+"",dataBean.getThroughput()+""));


                            } else if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 2) {
                                //美元
                                tv_Price.setText("$" + Util.GetTNumber(dataBean.getPrice()+""));
                                tv_rmoney.setText("≈ $ "+Util.Multiplication(dataBean.getPrice()+"",dataBean.getThroughput()+""));


                            }

                            tv_CostRate.setText(dataBean.getCostRate());
                            tv_StartPayAmount.setText(dataBean.getStartPayAmount());
                            tv_PayTime.setText(dataBean.getPayTime());


                        }
                    }
                }

                @Override
                public void onError(String msg) {
                    super.onError(msg);
                    loadingDialog.dismiss();
                    ToastUtil.showToast(MainstreamCurrencyDetaiAc.this, msg);
                }
            });
        }
        else
        {

            ToastUtil.showToast(MainstreamCurrencyDetaiAc.this,getResources().getString(R.string.internet_error));
        }


    }



    private void init()
    {
        spUtil = new SPUtil(MainstreamCurrencyDetaiAc.this, "fileName");
        loadingDialog = new LoadingDialog(this, 0);
        initSwitcher();

        edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                    if(dataBean!=null)
                    {
                        if(charSequence.toString().equals(""))
                        {
                            if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 1) {

                                //人民币币价
                                tv_Throughput.setText("0");
                                tv_rmoney.setText("≈ ￥ 0");

                            } else if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 2) {
                                //美元
                                tv_Throughput.setText("0");
                                tv_rmoney.setText("≈ $ 0");
                              }

                              return;
                          }

                         if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 1) {


                            BigDecimal bi1 = new BigDecimal(dataBean.getPrice());

                            BigDecimal bi2 = new BigDecimal(dataBean.getExchange() + "");
                            double s = bi1.multiply(bi2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            String st=Util.NMultiplication(Double.valueOf(charSequence.toString())+"",dataBean.getThroughput()+"");
                            //人民币币价
                            tv_Throughput.setText(st);
                            tv_rmoney.setText("≈ ￥ "+Util.Multiplication(s+"",st));


                        } else if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 2) {
                             String st=Util.NMultiplication(Double.valueOf(charSequence.toString())+"",dataBean.getThroughput()+"");
                            //美元
                            tv_Throughput.setText(st);
                            tv_rmoney.setText("≈ $ "+Util.Multiplication(dataBean.getPrice()+"",st));

//                            tv_Throughput.setText(dataBean.getThroughput() + " " + dataBean.getCode() + "≈$" + t);
                        }
                    }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 1) {
            kind=1;
            tv_money.setText("CNY");

        } else if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 2) {
            kind=2;
            tv_money.setText("USD");
        }
    }
    private void initSwitcher() {
        mywitcher.setChecked(true);
        tv_day.setTextColor(getResources().getColor(R.color.system_color));
        tv_minue.setTextColor(getResources().getColor(R.color.white));
        mywitcher.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //选中状态 可以做一些操作
                    //未选中状态 可以做一些操作
                    tv_day.setTextColor(getResources().getColor(R.color.system_color));
                    tv_minue.setTextColor(getResources().getColor(R.color.white));
                    day="30";
                     getPowChartDate(code,day,1);
                } else {
                    day="7";
                    tv_minue.setTextColor(getResources().getColor(R.color.system_color));
                    tv_day.setTextColor(getResources().getColor(R.color.white));
                    getPowChartDate(code,day,1);
                }
            }
        });

    }

    /**
     * 获取币种数据
     */
    private void getCurrrencyData() {
        currencyListData = new ArrayList<>();
        if (NetWorkUtil.check(this)) {
            loadingDialog.show();
            NetHelperNew.GetCurrencyList(new HttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String data) {
                    Log.i("-->", "币种列表：" + data);
                    CurrencyList currencyList = MyGson.getInstance().fromJson(data, CurrencyList.class);
                    if (currencyList.getType() == 1) {

                        currencyListData.addAll(currencyList.getData());
                        initCurrencyPopupWindow();
                        if (currencyList.getData().size() > 0) {
                            if (currencyId == 0) {
                                GlideUtil.loadImage(MainstreamCurrencyDetaiAc.this, NetHelperNew.URL + getIntent().getStringExtra("icon"), iv_curreney, R.mipmap.failimage, R.mipmap.failimage);
                                tv_currrncyname.setText(getIntent().getStringExtra("code").toUpperCase());
                                tv_title1.setText(getIntent().getStringExtra("code").toUpperCase()+" 全网算力");
                                tv_title2.setText(getIntent().getStringExtra("code").toUpperCase().toUpperCase()+" 价格走势");
                                currencyId = Integer.valueOf(getIntent().getStringExtra("position"));
                                code=getIntent().getStringExtra("code");
                            } else {

                                for (int i = 0; i < currencyList.getData().size(); i++) {
                                    if (currencyId == currencyList.getData().get(i).getId()) {
                                        GlideUtil.loadImage(MainstreamCurrencyDetaiAc.this, NetHelperNew.URL + currencyList.getData().get(i).getIcon(), iv_curreney, R.mipmap.failimage, R.mipmap.failimage);
                                        tv_currrncyname.setText(currencyList.getData().get(i).getCode().toUpperCase());
                                        code=currencyList.getData().get(i).getCode();
                                    }
                                }
                            }
                            getData();
                            getPowChartDate(code,day,0);
                        }
                        else
                        {
                            ToastUtil.showToast(MainstreamCurrencyDetaiAc.this, "没有数据");
                            loadingDialog.dismiss();

                        }

                    } else {
                        loadingDialog.dismiss();
                        new ErrorDialog(MainstreamCurrencyDetaiAc.this, currencyList.getContent()).show();
                    }
                }

                @Override
                public void onError(String msg) {
                    super.onError(msg);
                    loadingDialog.dismiss();
                    ToastUtil.showToast(MainstreamCurrencyDetaiAc.this, msg);
                }
            });


        }
        else
        {
            ToastUtil.showToast(MainstreamCurrencyDetaiAc.this,"网络连接异常");
        }

    }
    /**
     * 币种选择pop初始化
     */
    private void initCurrencyPopupWindow() {
        currencyPopupWindow = new CurrencyPopupWindow(currencyListData, MainstreamCurrencyDetaiAc.this, new CurrencyPopupWindow.OnSeleCurrencyLayoutListener() {
            @Override
            public void selectHouseLayout(int i) {
                currencyId = currencyListData.get(i).getId();
                code=currencyListData.get(i).getCode();
                GlideUtil.loadImage(MainstreamCurrencyDetaiAc.this, NetHelperNew.URL + currencyListData.get(i).getIcon(), iv_curreney, R.mipmap.failimage, R.mipmap.failimage);
                tv_currrncyname.setText(currencyListData.get(i).getCode().toUpperCase());
                tv_title1.setText(currencyListData.get(i).getCode().toUpperCase()+" 全网算力");
                tv_title2.setText(currencyListData.get(i).getCode().toUpperCase()+" 价格走势");
                loadingDialog.show();
                getData();
                getPowChartDate(code,day,0);
            }
        });
    }
    @OnClick({ R.id.ll_currency,R.id.iv_fz1,R.id.iv_fz2,R.id.iv_fz3,R.id.iv_left})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.ll_currency:
                //选择币种
                if (currencyPopupWindow != null)
                    currencyPopupWindow.showAsDropDown(ll_currency, 0, 0);
                break;
            case R.id.iv_fz1:
                Fz(tv_address1.getText().toString());
                break;
            case R.id.iv_fz2:
                Fz(tv_address2.getText().toString());
                break;

            case R.id.iv_fz3:
                Fz(tv_address3.getText().toString());
                break;
            case R.id.iv_left:
                finish();
                break;
        }
    }

    private void Fz(String str)
    {

        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        cm.setText(str);
        Toast.makeText(this, "复制成功", Toast.LENGTH_LONG).show();
    }

    /**
     * 获取图表数据
     * @param Code
     * @param Day
     */
    private void  getPowChartDate(String Code,String Day,final int k)
    {

        if(NetWorkUtil.checkNet(MainstreamCurrencyDetaiAc.this))
        {
            if(k==1)
            {
                loadingDialog.show();
            }
            NetHelperNew.PowCoinChart(Code, Day, new HttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String data) {
                    if(k==1)
                    {
                        loadingDialog.dismiss();
                    }
                    PowCoinChartBean powCoinChartBean = MyGson.getInstance().fromJson(data, PowCoinChartBean.class);
                    if(powCoinChartBean.getType()==1)
                    {

                        float max = 0;
                        float maxx = 0;
                        List<LineChartTestBean> list=new ArrayList<>();
                        List<PowCoinChartBean.DataBean.ChartDataBean> listt =powCoinChartBean.getData().getChartData();
                        String strU="",strUU="";
                        for (int i=0;i<listt.size();i++)
                        {
                            strU=listt.get(i).getHashrateUnit();
                            String date[]=listt.get(i).getCreatedTime().split(" ");
                            int m=date[0].length();
                            String time=date[0].substring(5,m);
                            String money="";
                            if(kind==1)
                            {
                                money=Util.Multiplication(listt.get(i).getPrice()+"",powCoinChartBean.getData().getExchange()+"");
                                strUU="￥";
                            }
                            else
                            {
                                strUU="$";
                                money=Util.GetTNumber(listt.get(i).getPrice()+"");
                            }

                            list.add(new LineChartTestBean(time, Float.valueOf(listt.get(i).getHashrate()+""),Float.valueOf(money)));
                        }



                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getFilingNumber() > max) {
                                max = list.get(i).getFilingNumber();
                            }
                            if (list.get(i).getTNumber() > maxx) {
                                maxx = list.get(i).getTNumber();
                            }
                        }
                        tv_u.setText(strU);
                        List<String> names = new ArrayList<>(); //折线名字集合
                        List<Integer> colour = new ArrayList<>();//折线颜色集合
                        //折线名字 //折线颜色
                        names.add("算力");
                        names.add("价钱");
                        colour.add(getResources().getColor(R.color.line_blue));
                        colour.add(getResources().getColor(R.color.line_orange));
                        dynamicLineChartManager2 = new DynamicLineChartDetailManager(mChart2, names, colour, 30, strU,strUU);
                        dynamicLineChartManager2.setDescription("");
                        dynamicLineChartManager2.setYAxis(max, 0, 6,maxx,0);
                        for (int i = 0; i < list.size(); i++) {
                            dynamicLineChartManager2.addEntry(list.get(i),i,list);
                        }

                    }

                }

                @Override
                public void onError(String msg) {
                    super.onError(msg);
                    if(k==1)
                    {
                        loadingDialog.dismiss();
                    }
                }
            });
        }
        else
        {

            ToastUtil.showToast(MainstreamCurrencyDetaiAc.this,getResources().getString(R.string.internet_error));
        }


    }

}
